package autokey;

import java.sql.*;
//如何得到返回的新记录的自增长的主键？
public class GetAutoKey {

	public static void main(String[] args) {
		Connection con = Jdbc.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "insert into subject(subjectname,classhour,gradeid) values(?,?,?)";
		try {
			ps = con.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);//return_generate_keys ：常数表示生成的密钥应该可用于检索。 
			ps.setString(1, "java高级特性");
			ps.setInt(2, 8);
			ps.setInt(3, 5);
			int row = ps.executeUpdate();
			// 获取自增长列，注意该方法
			rs = ps.getGeneratedKeys();  //getGeneratedKeys检索由执行此Statement对象而创建的任何自动生成的密钥
			if (rs.next()) {
				long id = rs.getLong(1);
				System.out.print("-----预定义SQL模式-----id =" + id);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			Jdbc.close(con, ps, rs);
		}
		
		//方式2：
		/*Connection conn = null;  
		Serializable ret = null;  
		PreparedStatement state = .;  
		ResultSet rs=null;  
		try {  
		     state.executeUpdate();  
		     rs = state.getGeneratedKeys();  
		     if (rs.next()) {  
		         ret = (Serializable) rs.getObject(1);  
		      }         
		     } catch (SQLException e) {  
		     }   
		  return ret; */
	}

}

